package com.lyl.servicebase.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
    // 全局配置跨域问题
    @Override
    public void addCorsMappings (CorsRegistry registry) {
        System.out.println("全局跨域配置");
        registry . addMapping("/**").
                   allowedOrigins("*")
                  . allowedMethods ("PUT","DELETE", "GET", "POST" ,"OPTIONS")
                  . allowedHeaders ("*")
//                    .exposedHeaders ("Access-Control-Allow-Origin",
//                            "Access-Control-Request-Headers","token","content-type")
                             . allowCredentials(true) .maxAge (3600) ;
    }
//    @Override
//    public void addCorsMappings (CorsRegistry registry) {
//        registry.
//                addMapping("/**" ).allowedHeaders("*")
//                .exposedHeaders("access-control-allow-headers",
//                               "access-control-allow-methods",
//                        "access-control-allow-origin",
//                        "access-control-max-age",
//                        "X-Frame-Options"                        )
//        .allowedOrigins("*")
//        .allowedMethods ( "POST", "GET", "PUT", "OPTIONS", "DELETE")
//        .maxAge (3600)
//        .allowCredentials(true) ;
//    }


    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter= new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper= new ObjectMapper();

        /*
        转换
         */
        SimpleModule simpleModule= new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE,ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);

        converters.add(jackson2HttpMessageConverter);







    }
}
